package com.gcxy.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gcxy.entity.City;
import com.gcxy.mapper.CityMapper;
import com.gcxy.service.CityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gcxy.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.gcxy.vo.CityVo;

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 基础表-省市区 服务实现类
 * </p>
 *
 * @author wlp
 * @since 2023-12-20
 */
@Service
public class CityServiceImpl extends ServiceImpl<CityMapper, City> implements CityService {
    @Autowired
    private CityMapper cityMapper;

    private List<CityVo> buildCityTree(List<City> cities, Integer parentid){
        List<CityVo> result=new ArrayList<>();
        for(City city:cities){
            if (city.getParentId()==parentid){
                List<CityVo> children=buildCityTree(cities,city.getId().intValue());
                CityVo cityVo=CityVo.builder()
                        .id(city.getId())
                        .name(city.getName())
                        .acronym(city.getAcronym())
                        .sort(city.getSort())
                        .updateTime(city.getUpdateTime())
                        .level(city.getLevel())
                        .parentId(city.getParentId())
                        .createTime(city.getCreateTime())
                        .code(city.getCode())
                        .children(children)
                        .build();
                result.add(cityVo);
            }
        }
        return result;
    }
    @Override
    public R getProvince() {
        LambdaQueryWrapper queryWrapper=new LambdaQueryWrapper<>();
        List<City> cities = cityMapper.selectList(queryWrapper);
        List<CityVo> cityVo=buildCityTree(cities,0);
        return R.Success(cityVo);
    }
}
